package com.jic.order.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.common.redis.RedisClientTemplate;
import com.jic.order.entity.*;
import com.jic.order.mapper.*;
import com.jic.order.rest.response.OrderBaleDeliveryResponse;
import com.jic.order.service.OrderBaleService;
import com.jic.product.after.api.ProductCommentApi;
import com.jic.manager.api.rest.ManagerStoreApi;
import com.jic.manager.response.MemStoreResponse;
import com.jic.market.api.rest.GrouponRestApi;
import com.jic.order.base.BaseService;
import com.jic.order.constant.consist.ResponseCode;
import com.jic.order.enums.OperatorActionEnum;
import com.jic.order.enums.OrderStatusEnum;
import com.jic.order.exception.AppRuntimeException;
import com.jic.order.model.domain.OrderStatusCountModel;
import com.jic.order.request.CommonOrderNoRequest;
import com.jic.order.request.OrderDeliverDetailRequest;
import com.jic.order.request.OrderDeliverQueryPage;
import com.jic.order.request.UserPageQuery;
import com.jic.order.request.UserQuery;
import com.jic.order.response.FrontAllOrderInfo;
import com.jic.order.response.FrontOrderDetailInfo;
import com.jic.order.response.FrontOrderGoodsInfo;
import com.jic.order.response.FrontOrderStatusCountInfo;
import com.jic.order.response.OrderDeliverInfo;
import com.jic.order.response.OrderDetailInfo;
import com.jic.order.rest.request.OrderSensitiveRequest;
import com.jic.order.rest.response.ProductCommentRestResponse;
import com.jic.order.service.OrderQueryService;
import com.jic.order.utils.SerialNoUtil;
import com.jic.product.after.api.ProductListApi;
import com.jic.product.after.response.ProductAfterInfoByIdResponse;

import java.util.*;
import java.util.stream.Collectors;
import javax.annotation.Resource;

import com.jic.product.rest.response.ProductPropertyResponse;
import com.jic.product.store.request.ProductCommentRequest;
import com.jic.product.store.response.ProductCommentResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class OrderQueryServiceImpl extends BaseService implements OrderQueryService {

    @Autowired
    RedisClientTemplate redisClientTemplate;
    @Resource
    ProductCommentApi productCommentRestApi;
    @Resource
    ManagerStoreApi managerStoreApi;
    @Resource
    ProductListApi productListApi;
    @Resource
    GrouponRestApi grouponRestApi;

    @Autowired
    private OrderParentMapper orderParentMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderGoodsMapper orderGoodsMapper;
    @Autowired
    private OrderAfterSaleApplyMapper orderAfterSaleApplyMapper;
    @Autowired
    private OrderDeliverMapper orderDeliverMapper;
    @Autowired
    private OrderDeliverDetailMapper orderDeliverDetailMapper;
    @Autowired
    private OrderProcessLogMapper orderProcessLogMapper;

    @Autowired
    private OrderMergeMapper orderMergeMapper;

    @Autowired
    private OrderBaleDeliveryMapper orderBaleDeliveryMapper;

    @Override
    public RestResult<List<FrontAllOrderInfo>> queryAllList(UserPageQuery request) {
        // 获取用户id
        String userStr = redisClientTemplate.get("H5_LOGIN_TOKEN_" + request.getToken());
        if (StringUtils.isEmpty(userStr)) {
            return RestResult.error("4000", "登录失效");
        }
        Map<String, Object> userMap = JSONArray.parseObject(userStr, HashMap.class);
        String userId = userMap.get("id").toString();

        log.info("查询订单分页，request={}", JSON.toJSONString(request));
        // 查询订单状态
        List<Integer> orderStatusList = null;
        if (StringUtils.isEmpty(request.getParentOrderNo()) && StringUtils.isEmpty(request.getGoodsName())) {
            orderStatusList = getOrderStatus(request.getOrderStatus());
        }
        // 查询商品名称
        List<String> orderNoList = null;
        if (StringUtils.isNotEmpty(request.getGoodsName())) {
            orderNoList = orderGoodsMapper.queryOrderNoByGoodsName(request.getGoodsName());
        }

        List<FrontAllOrderInfo> frontAllOrderInfoList = new ArrayList<>();

        // 查询父订单
        int startIndex = (request.getStart() - 1) * request.getLimit();
        List<OrderParent> orderParentList = orderParentMapper.queryOrderPage(startIndex, request.getLimit(),
                Long.valueOf(userId), request.getParentOrderNo(), orderNoList, orderStatusList);

        // 查询子订单
        if (null != orderParentList && !orderParentList.isEmpty()) {
            for (OrderParent orderParent : orderParentList) {
                FrontAllOrderInfo frontAllOrderInfo = new FrontAllOrderInfo();
                BeanUtils.copyProperties(orderParent, frontAllOrderInfo);
                if (orderParent.getPaymentExpire() != null){
                    frontAllOrderInfo.setPaymentCountDown(orderParent.getPaymentExpire().getTime());
                }

                // 集合存储订单详情信息
                List<FrontOrderDetailInfo> frontOrderDetailInfoList = new ArrayList<>();

                // 根据父订单号查询订单信息
                Order orderQ = new Order();
                orderQ.setParentOrderNo(orderParent.getParentOrderNo());
                List<Order> orderList = orderMapper.query(orderQ);
                if (null != orderList && !orderList.isEmpty()) {
                    for (Order order : orderList) {
                        FrontOrderDetailInfo orderDetailInfo = new FrontOrderDetailInfo();
                        BeanUtils.copyProperties(order, orderDetailInfo);
                        // 查询订单商品明细
                        OrderGoods orderGoodsQ = new OrderGoods();
                        orderGoodsQ.setOrderNo(order.getOrderNo());
                        List<OrderGoods> orderGoodsList = orderGoodsMapper.query(orderGoodsQ);
                        if (null != orderGoodsList && !orderGoodsList.isEmpty()) {
                            List<FrontOrderGoodsInfo> goodsInfoList = new ArrayList<>();
                            for (OrderGoods orderGoods : orderGoodsList) {
                                FrontOrderGoodsInfo frontOrderGoodsInfo = new FrontOrderGoodsInfo();
                                RestResult<List<ProductPropertyResponse>> listRestResult = productListApi.queryProductPropetyBySpuId(Long.valueOf(orderGoods.getGoodsId()));
                                if (null != listRestResult && null != listRestResult.getData()) {
                                    orderGoods.setProductPropertyResponses(listRestResult.getData());
                                }
                                BeanUtils.copyProperties(orderGoods, frontOrderGoodsInfo);
                                goodsInfoList.add(frontOrderGoodsInfo);
                            }
                            orderDetailInfo.setGoodsInfoList(goodsInfoList);
                        }
                        frontOrderDetailInfoList.add(orderDetailInfo);
                    }
                }
                frontAllOrderInfo.setOrderList(frontOrderDetailInfoList);
                frontAllOrderInfoList.add(frontAllOrderInfo);
            }
        }

        return RestResult.success(frontAllOrderInfoList);
    }


    /**
     * description: getOrderStatus
     *
     * @author: jackHe
     * @time: 2020/8/11 16:29
     */
    private List<Integer> getOrderStatus(Integer orderStatus) {
        List<Integer> orderStatusList = new ArrayList<>(5);
        if (null == orderStatus || 0 == orderStatus) {
            orderStatusList = null;
        } else {
            orderStatusList.add(orderStatus);
            // 待评价兼容确认收货
            if (OrderStatusEnum.WAIT_REVIEW.getCode().equals(orderStatus)) {
                orderStatusList.add(OrderStatusEnum.CONFIRM_SHIP.getCode());
            }
            // 待发货和已支付兼容
            if (OrderStatusEnum.WAIT_SHIP.getCode().equals(orderStatus)) {
                orderStatusList.add(OrderStatusEnum.ALREADY_PAY.getCode());
            }
            // 已支付和待发货兼容
            if (OrderStatusEnum.ALREADY_PAY.getCode().equals(orderStatus)) {
                orderStatusList.add(OrderStatusEnum.WAIT_SHIP.getCode());
            }
        }
        return orderStatusList;
    }

    @Override
    public RestResult<FrontAllOrderInfo> queryDetail(CommonOrderNoRequest request) {
        // 获取父订单编号
        String parentOrderNo = null;
        String orderNo = null;
        if (SerialNoUtil.isParentOrderNo(request.getOrderNo())) {
            parentOrderNo = request.getOrderNo();
        } else if (SerialNoUtil.isOrderNo(request.getOrderNo())) {
            orderNo = request.getOrderNo();
        } else {
            return null;
        }

        // 存储父订单详情信息
        Order orderReq = new Order();
        orderReq.setOrderNo(orderNo);
        orderReq.setParentOrderNo(parentOrderNo);
        OrderParent orderParent = orderParentMapper.queryOrderParentInfo(orderReq);
        if (null == orderParent) {
            log.error("订单不存在，orderNo:{}", request.getOrderNo());
            return RestResult.error("9999", "订单不存在");
        }

        FrontAllOrderInfo frontAllOrderInfo = new FrontAllOrderInfo();
        BeanUtils.copyProperties(orderParent, frontAllOrderInfo);
        if (orderParent.getPaymentExpire() != null){
            frontAllOrderInfo.setPaymentCountDown(orderParent.getPaymentExpire().getTime());
        }

        // 集合存储子订单详情信息
        List<FrontOrderDetailInfo> frontOrderDetailInfoList = new ArrayList<>();
        Order orderQ = new Order();
        orderQ.setOrderNo(orderNo);
        orderQ.setParentOrderNo(parentOrderNo);
        List<Order> orderList = orderMapper.query(orderQ);
        if (null != orderList && !orderList.isEmpty()) {
            //       todo 前端直接调拼团信息(等待讨论)
            //			if (StringUtils.isNotEmpty(orderList.get(0).getGroupId())) {
            //				LaunchGrouponDetailRequest grouponDetailRequest = new LaunchGrouponDetailRequest();
            //				grouponDetailRequest.setGroupCode(orderList.get(0).getGroupId());
            //				RestResult<LaunchGrouponDetailResponse> grouponDetailResponseRestResult = grouponRestApi.launchGrouponDetail(grouponDetailRequest);
            //			}

            for (Order order : orderList) {
                FrontOrderDetailInfo orderDetailInfo = new FrontOrderDetailInfo();
                BeanUtils.copyProperties(order, orderDetailInfo);

                OrderGoods orderGoodsQ = new OrderGoods();
                orderGoodsQ.setOrderNo(order.getOrderNo());
                List<OrderGoods> orderGoodsList = orderGoodsMapper.query(orderGoodsQ);
                if (null != orderGoodsList && !orderGoodsList.isEmpty()) {
                    List<FrontOrderGoodsInfo> goodsInfoList = new ArrayList<>();
                    // 商品信息
                    for (OrderGoods orderGoods : orderGoodsList) {
                        FrontOrderGoodsInfo frontOrderGoodsInfo = new FrontOrderGoodsInfo();

                        // 商品评价
                        if (OrderStatusEnum.FINISH.getCode().equals(order.getOrderStatus())) {
                            ProductCommentRequest productCommentRequest = new ProductCommentRequest();
                            productCommentRequest.setProductId(orderGoods.getGoodsId());
                            productCommentRequest.setOrderNo(orderGoods.getOrderNo());
                            RestResult<ProductCommentResponse> restResult = productCommentRestApi.getProductCommentByOrderNo(productCommentRequest);
                            ProductCommentRestResponse productComment = new ProductCommentRestResponse();
                            BeanUtils.copyProperties(restResult.getData(), productComment);
                            frontOrderGoodsInfo.setProductComment(productComment);
                        }
                        RestResult<List<ProductPropertyResponse>> listRestResult = productListApi.queryProductPropetyBySpuId(Long.valueOf(orderGoods.getGoodsId()));
                        if (null != listRestResult && null != listRestResult.getData()) {
                            orderGoods.setProductPropertyResponses(listRestResult.getData());
                        }
                        BeanUtils.copyProperties(orderGoods, frontOrderGoodsInfo);
                        goodsInfoList.add(frontOrderGoodsInfo);
                    }
                    orderDetailInfo.setGoodsInfoList(goodsInfoList);
                    // 查询物流信息
                    if (order.getOrderStatus() >= OrderStatusEnum.ALREADY_SHIP.getCode()) {
                        OrderBaleDelivery baleDelivery = new OrderBaleDelivery() {{
                            setOrderNo(order.getOrderNo());
                        }};
                        OrderBaleDelivery orderBaleDelivery = orderBaleDeliveryMapper.queryDeliveryByOrderNo(baleDelivery);
                        OrderBaleDeliveryResponse baleDeliveryResponse = new OrderBaleDeliveryResponse();
                        if (orderBaleDelivery != null) {
                            BeanUtils.copyProperties(orderBaleDelivery, baleDeliveryResponse);
                            orderDetailInfo.setOrderBaleDeliveryResponse(baleDeliveryResponse);
                        }
                    }


                }
                frontOrderDetailInfoList.add(orderDetailInfo);
            }

            // 订单操作时间
            OrderProcessLog orderProcessLog = new OrderProcessLog();
            orderProcessLog.setOrderNo(orderList.get(0).getOrderNo());
            List<OrderProcessLog> processLogs = orderProcessLogMapper.query(orderProcessLog);
            for (OrderProcessLog processLog : processLogs) {
                OperatorActionEnum operatorActionEnum = OperatorActionEnum.getByCode(processLog.getOperatorAction());
                Optional.ofNullable(operatorActionEnum).ifPresent(item -> {
                    switch (operatorActionEnum) {
                        case USER_CREATE:
                            frontAllOrderInfo.setCreateTime(processLog.getOperatorTime());
                            break;
                        case USER_PAY:
                            frontAllOrderInfo.setPaymentTime(processLog.getOperatorTime());
                            break;
                        case SEND_GOODS:
                            frontAllOrderInfo.setDeliveryTime(processLog.getOperatorTime());
                            break;
                        case CONFIRM_RECEIPT:
                            frontAllOrderInfo.setCompleteTime(processLog.getOperatorTime());
                            break;
                        default:
                            break;
                    }
                });
            }
        }


        frontAllOrderInfo.setOrderList(frontOrderDetailInfoList);
        return RestResult.success(frontAllOrderInfo);
    }

    @Override
    public List<FrontAllOrderInfo> getOrderSensitiveList(OrderSensitiveRequest orderSensitiveRequest) {
        OrderParent orderParentQ = new OrderParent();
        orderParentQ.setBuyerId(orderSensitiveRequest.getUserId());
        List<Integer> orderStatusList = new ArrayList<>();
        //待评价兼容
        if (OrderStatusEnum.WAIT_REVIEW.getCode().equals(orderSensitiveRequest.getOrderStatus())
                || OrderStatusEnum.WHOLE.getCode().equals(orderSensitiveRequest.getOrderStatus())) {
            orderStatusList.add(OrderStatusEnum.WAIT_REVIEW.getCode());
        }
        if (OrderStatusEnum.FINISH.getCode().equals(orderSensitiveRequest.getOrderStatus())
                || OrderStatusEnum.WHOLE.getCode().equals(orderSensitiveRequest.getOrderStatus())) {
            orderStatusList.add(OrderStatusEnum.FINISH.getCode());
        }
        if (null == orderSensitiveRequest.getOrderStatus() || 0 == orderSensitiveRequest.getOrderStatus()) {
            orderStatusList = null;
        }
        return this.frontAllOrderInfoList(orderSensitiveRequest.getStart(), orderSensitiveRequest.getLimit(), orderParentQ, orderStatusList);
    }

    private List<FrontAllOrderInfo> frontAllOrderInfoList(int start, int limit, OrderParent orderParentQ, List<Integer> orderStatusList) {
        List<FrontAllOrderInfo> frontAllOrderInfoList = new ArrayList<>();
        // 查询父订单
        int startIndex = (start - 1) * limit;
        List<OrderParent> orderParentList = orderParentMapper.queryPage(startIndex, limit, orderParentQ, orderStatusList);

        // 查询子订单
        if (null != orderParentList && !orderParentList.isEmpty()) {
            for (OrderParent orderParent : orderParentList) {
                FrontAllOrderInfo frontAllOrderInfo = new FrontAllOrderInfo();
                BeanUtils.copyProperties(orderParent, frontAllOrderInfo);

                // 集合存储订单详情信息
                List<FrontOrderDetailInfo> frontOrderDetailInfoList = new ArrayList<>();

                // 根据父订单号查询订单信息
                Order orderQ = new Order();
                orderQ.setParentOrderNo(orderParent.getParentOrderNo());
                List<Order> orderList = orderMapper.query(orderQ);
                if (null != orderList && !orderList.isEmpty()) {
                    for (Order order : orderList) {
                        FrontOrderDetailInfo orderDetailInfo = new FrontOrderDetailInfo();
                        BeanUtils.copyProperties(order, orderDetailInfo);
                        // 查询订单商品明细
                        OrderGoods orderGoodsQ = new OrderGoods();
                        orderGoodsQ.setOrderNo(order.getOrderNo());
                        List<OrderGoods> orderGoodsList = orderGoodsMapper.query(orderGoodsQ);
                        if (null != orderGoodsList && !orderGoodsList.isEmpty()) {
                            List<FrontOrderGoodsInfo> goodsInfoList = new ArrayList<>();
                            for (OrderGoods orderGoods : orderGoodsList) {
                                FrontOrderGoodsInfo frontOrderGoodsInfo = new FrontOrderGoodsInfo();
                                BeanUtils.copyProperties(orderGoods, frontOrderGoodsInfo);
                                goodsInfoList.add(frontOrderGoodsInfo);
                            }
                            orderDetailInfo.setGoodsInfoList(goodsInfoList);
                        }

                        frontOrderDetailInfoList.add(orderDetailInfo);
                    }
                }

                frontAllOrderInfo.setOrderList(frontOrderDetailInfoList);
                frontAllOrderInfoList.add(frontAllOrderInfo);
            }
        }
        return frontAllOrderInfoList;
    }

    @Override
    public RestResult<FrontOrderStatusCountInfo> queryMyOrderStatusCount(Long buyerId) {
        List<OrderStatusCountModel> myAllOrderStatus = orderParentMapper.queryMyAllOrderStatus(buyerId);
        if (null != myAllOrderStatus && myAllOrderStatus.size() > 0) {
            FrontOrderStatusCountInfo result = new FrontOrderStatusCountInfo();
            int alreadyPay = 0;
            int waitShip = 0;
            int confirmShip = 0;
            int waitReview = 0;
            for (OrderStatusCountModel allOrderStatus : myAllOrderStatus) {
                OrderStatusEnum orderStatusEnum = OrderStatusEnum.getByCode(allOrderStatus.getOrderStatus());
                Optional.ofNullable(orderStatusEnum).orElseThrow(() -> new AppRuntimeException(ResponseCode.EXCEPTION, "该订单状态不存在"));
                switch (orderStatusEnum) {
                    case WAIT_PAY:
                        result.setWaitPayCount(allOrderStatus.getOrderStatusCount());
                        break;
                    case ALREADY_PAY:
                        alreadyPay = allOrderStatus.getOrderStatusCount();
                        break;
                    case WAIT_SHIP:
                        waitShip = allOrderStatus.getOrderStatusCount();
                        break;
                    case ALREADY_SHIP:
                        result.setAlreadyShipCount(allOrderStatus.getOrderStatusCount());
                        break;
                    case CONFIRM_SHIP:
                        confirmShip = allOrderStatus.getOrderStatusCount();
                        break;
                    case WAIT_REVIEW:
                        waitReview = allOrderStatus.getOrderStatusCount();
                        break;
                    default:
                        break;
                }
            }
            // 待发货和已支付兼容
            result.setWaitShipCount(alreadyPay + waitShip);
            // 待评价兼容确认收货
            result.setWaitReviewCount(confirmShip + waitReview);
            result.setAfterSaleCount(orderAfterSaleApplyMapper.queryAfterSaleCountByMemberId(buyerId));
            return RestResult.success(result);
        }
        return RestResult.success(new FrontOrderStatusCountInfo());
    }

    @Override
    public RestResult<FrontOrderStatusCountInfo> queryOrderStatusCount(UserQuery request) {
        log.info("查询订单状态统计，request={}", JSON.toJSONString(request));
        return executeQuery(() -> {
            Integer afterSaleCount = 0;
            Integer waitPayCount = 0;
            Integer waitShipCount = 0;
            Integer alreadyShipCount = 0;
            Integer waitReviewCount = 0;

            List<OrderParent> orderParentList = orderParentMapper.query(new OrderParent() {{
                setBuyerId(request.getUserId());
            }});
            if (null != orderParentList && orderParentList.size() > 0) {
                for (OrderParent orderParent : orderParentList) {
                    if (null != orderParent.getOrderStatus()) {
                        if (OrderStatusEnum.WAIT_PAY.getCode().equals(orderParent.getOrderStatus())) {
                            waitPayCount++;
                        } else if (OrderStatusEnum.WAIT_SHIP.getCode().equals(orderParent.getOrderStatus()) ||
                                OrderStatusEnum.ALREADY_PAY.getCode().equals(orderParent.getOrderStatus())) {
                            waitShipCount++;
                        } else if (OrderStatusEnum.ALREADY_SHIP.getCode().equals(orderParent.getOrderStatus())) {
                            alreadyShipCount++;
                        }
                        //待评价兼容
                        else if (OrderStatusEnum.CONFIRM_SHIP.getCode().equals(orderParent.getOrderStatus())) {
                            waitReviewCount++;
                        }
                    }
                }
            }

            // 售后统计
            FrontOrderStatusCountInfo countInfo = new FrontOrderStatusCountInfo();
            afterSaleCount = orderAfterSaleApplyMapper.orderAfterSaleApplyQueryPageCount(new OrderAfterSaleApplyModel() {{
                setMemberId(request.getUserId());
            }});

            countInfo.setAfterSaleCount(afterSaleCount);
            countInfo.setAlreadyShipCount(alreadyShipCount);
            countInfo.setWaitPayCount(waitPayCount);
            countInfo.setWaitReviewCount(waitReviewCount);
            countInfo.setWaitShipCount(waitShipCount);
            return countInfo;
        });
    }

    @Override
    public RestResult<PageResult<OrderDeliverInfo>> queryDeliverPage(OrderDeliverQueryPage orderDeliverQueryPage) {
        log.info("查询交货单分页，request={}", JSON.toJSONString(orderDeliverQueryPage));
        return executeQuery(() -> {
            // 计算下标
            int startIndex = (orderDeliverQueryPage.getStart() - 1) * orderDeliverQueryPage.getLimit();
            List<OrderDeliverInfo> list = orderDeliverMapper.queryPage(startIndex, orderDeliverQueryPage.getLimit(), orderDeliverQueryPage);
            long count = orderDeliverMapper.queryPageCount(orderDeliverQueryPage);
            PageResult pageResult = new PageResult();
            pageResult.setRows(list);
            pageResult.setTotal(count);
            return pageResult;
        });
    }


    @Override
    public RestResult<List<OrderDeliverInfo>> queryOrderByMergeRule(OrderDeliverQueryPage request) {
        log.info("根据合并规则查询交货单，request={}", JSON.toJSONString(request));
        List<OrderMerge> rules = orderMergeMapper.query(new OrderMerge() {{
            setDeleteFlag(0L);
            setStatus(1L);
            setDeptId(request.getAdminOperate().getDeptId() == null ? null : request.getAdminOperate().getDeptId());
        }});
        OrderDeliverQueryPage orderDeliver = new OrderDeliverQueryPage();
        orderDeliver.setOrderStatus(3);
        //前端下单的不无法确定哪个组织
        orderDeliver.setAdminOperate(request.getAdminOperate());
        List<OrderDeliverInfo> orders = orderDeliverMapper.queryList(orderDeliver);
        if (CollectionUtil.isEmpty(orders)) {
            return new RestResult<List<OrderDeliverInfo>>();
        }
        List<OrderMerge> mergeList = new ArrayList<>();
        for (OrderMerge rule : rules) {
            if (rule.getPriority() != null) {
                mergeList.add(rule);
            }
        }
        if (CollectionUtil.isNotEmpty(rules)) {
            OrderMerge rule = mergeList.stream().max(Comparator.comparing(OrderMerge::getPriority)).get();
            String splitType = rule.getSplitType();
            String[] types = StringUtils.isNotEmpty(splitType) ? splitType.split(",") : null;//1.2.3
            if (types != null) {
                if (Arrays.asList(types).contains("1") && Arrays.asList(types).contains("2") && Arrays.asList(types).contains("3")) {
                    Map<String, Map<String, List<OrderDeliverInfo>>> group = orders.stream()
                            .collect(Collectors.groupingBy(OrderDeliverInfo::getReceiverPhone, Collectors.groupingBy(OrderDeliverInfo::getReceiverName)));
                    ArrayList<OrderDeliverInfo> infos = new ArrayList<>();
                    if (!group.isEmpty()) {
                        for (Map.Entry<String, Map<String, List<OrderDeliverInfo>>> entry : group.entrySet()) {
                            for (Map.Entry<String, List<OrderDeliverInfo>> listEntry : entry.getValue().entrySet()) {
                                if (listEntry.getValue().size() > 1) {
                                    infos.addAll(listEntry.getValue());
                                }
                            }
                        }
                    }
                    Map<String, List<OrderDeliverInfo>> collect = infos.stream().collect(Collectors.groupingBy(OrderDeliverInfo::getReceiverAddress));
                    if (!collect.isEmpty()) {
                        infos.removeAll(infos);
                        for (Map.Entry<String, List<OrderDeliverInfo>> entry : collect.entrySet()) {
                            if (entry.getValue().size() > 1) {
                                infos.addAll(entry.getValue());
                            }
                        }
                    }
                }
                if (Arrays.asList(types).contains("1") && Arrays.asList(types).contains("2")) {
                    Map<String, Map<String, List<OrderDeliverInfo>>> group = orders.stream()
                            .collect(Collectors.groupingBy(OrderDeliverInfo::getReceiverPhone, Collectors.groupingBy(OrderDeliverInfo::getReceiverName)));
                    ArrayList<OrderDeliverInfo> infos = new ArrayList<>();
                    if (!group.isEmpty()) {
                        for (Map.Entry<String, Map<String, List<OrderDeliverInfo>>> entry : group.entrySet()) {
                            for (Map.Entry<String, List<OrderDeliverInfo>> listEntry : entry.getValue().entrySet()) {
                                if (listEntry.getValue().size() > 1) {
                                    infos.addAll(listEntry.getValue());
                                }
                            }
                        }
                    }
                    return RestResult.success(infos);
                }
                if (Arrays.asList(types).contains("1")) {
                    Map<String, List<OrderDeliverInfo>> collect = orders.stream().collect(Collectors.groupingBy(OrderDeliverInfo::getReceiverName));
                    ArrayList<OrderDeliverInfo> infos = new ArrayList<>();
                    if (!collect.isEmpty()) {
                        for (Map.Entry<String, List<OrderDeliverInfo>> entry : collect.entrySet()) {
                            if (entry.getValue().size() > 1) {
                                infos.addAll(entry.getValue());
                            }
                        }
                    }
                    return RestResult.success(infos);
                }


            } else {
                //根据姓名、手机号、地址匹配
                Map<String, Map<String, List<OrderDeliverInfo>>> group = orders.stream()
                        .collect(Collectors.groupingBy(OrderDeliverInfo::getReceiverPhone, Collectors.groupingBy(OrderDeliverInfo::getReceiverName)));
                ArrayList<OrderDeliverInfo> infos = new ArrayList<>();
                if (!group.isEmpty()) {
                    for (Map.Entry<String, Map<String, List<OrderDeliverInfo>>> entry : group.entrySet()) {
                        for (Map.Entry<String, List<OrderDeliverInfo>> listEntry : entry.getValue().entrySet()) {
                            if (listEntry.getValue().size() > 1) {
                                infos.addAll(listEntry.getValue());
                            }
                        }
                    }
                }
                Map<String, List<OrderDeliverInfo>> collect = infos.stream().collect(Collectors.groupingBy(OrderDeliverInfo::getReceiverAddress));
                if (!collect.isEmpty()) {
                    infos.removeAll(infos);
                    for (Map.Entry<String, List<OrderDeliverInfo>> entry : collect.entrySet()) {
                        if (entry.getValue().size() > 1) {
                            infos.addAll(entry.getValue());
                        }
                    }
                }
            }

        } else {
            //根据姓名、手机号、地址匹配
            Map<String, Map<String, List<OrderDeliverInfo>>> group = orders.stream()
                    .collect(Collectors.groupingBy(OrderDeliverInfo::getReceiverPhone, Collectors.groupingBy(OrderDeliverInfo::getReceiverName)));
            ArrayList<OrderDeliverInfo> infos = new ArrayList<>();
            if (!group.isEmpty()) {
                for (Map.Entry<String, Map<String, List<OrderDeliverInfo>>> entry : group.entrySet()) {
                    for (Map.Entry<String, List<OrderDeliverInfo>> listEntry : entry.getValue().entrySet()) {
                        if (listEntry.getValue().size() > 1) {
                            infos.addAll(listEntry.getValue());
                        }
                    }
                }
            }
            Map<String, List<OrderDeliverInfo>> collect = infos.stream().collect(Collectors.groupingBy(OrderDeliverInfo::getReceiverAddress));
            if (!collect.isEmpty()) {
                infos.removeAll(infos);
                for (Map.Entry<String, List<OrderDeliverInfo>> entry : collect.entrySet()) {
                    if (entry.getValue().size() > 1) {
                        infos.addAll(entry.getValue());
                    }
                }
            }
        }


        return null;
    }

    @Override
    public RestResult<List<FrontAllOrderInfo>> queryPickAllList(UserPageQuery request) {
        // 获取用户id
        String userStr = redisClientTemplate.get("H5_LOGIN_TOKEN_" + request.getToken());
        if (StringUtils.isEmpty(userStr)) {
            return RestResult.error("4000", "登录失效");
        }
        Map<String, Object> userMap = JSONArray.parseObject(userStr, HashMap.class);
        String userId = userMap.get("id").toString();

        log.info("查询订单分页，request={}", JSON.toJSONString(request));
        // 查询订单状态
        List<Integer> orderStatusList = null;
        if (StringUtils.isEmpty(request.getParentOrderNo()) && StringUtils.isEmpty(request.getGoodsName())) {
            orderStatusList = getOrderStatus(request.getOrderStatus());
        }
        // 查询商品名称
        List<String> orderNoList = null;
        if (StringUtils.isNotEmpty(request.getGoodsName())) {
            orderNoList = orderGoodsMapper.queryOrderNoByGoodsName(request.getGoodsName());
        }

        List<FrontAllOrderInfo> frontAllOrderInfoList = new ArrayList<>();

        // 查询父订单
        int startIndex = (request.getStart() - 1) * request.getLimit();
        List<OrderParent> orderParentList = orderParentMapper.queryOrderPage(startIndex, request.getLimit(),
                Long.valueOf(userId), request.getParentOrderNo(), orderNoList, orderStatusList);

        // 查询子订单
        if (null != orderParentList && !orderParentList.isEmpty()) {
            for (OrderParent orderParent : orderParentList) {
                FrontAllOrderInfo frontAllOrderInfo = new FrontAllOrderInfo();
                BeanUtils.copyProperties(orderParent, frontAllOrderInfo);

                // 集合存储订单详情信息
                List<FrontOrderDetailInfo> frontOrderDetailInfoList = new ArrayList<>();

                // 根据父订单号查询订单信息
                Order orderQ = new Order();
                orderQ.setParentOrderNo(orderParent.getParentOrderNo());
                List<Order> orderList = orderMapper.query(orderQ);
                if (null != orderList && !orderList.isEmpty()) {
                    for (Order order : orderList) {
                        FrontOrderDetailInfo orderDetailInfo = new FrontOrderDetailInfo();
                        // 查询订单商品明细
                        OrderGoods orderGoodsQ = new OrderGoods();
                        orderGoodsQ.setOrderNo(order.getOrderNo());
                        List<OrderGoods> orderGoodsList = orderGoodsMapper.query(orderGoodsQ);
                        //只查改订单名一下件商品 orderGoodsList.size() ==1
                        if (CollectionUtils.isNotEmpty(orderGoodsList) && orderGoodsList.size() == 1) {
                            List<FrontOrderGoodsInfo> goodsInfoList = new ArrayList<>();
                            for (OrderGoods orderGoods : orderGoodsList) {
                                RestResult<ProductAfterInfoByIdResponse> productAfterInfoByIdResponseRestResult =
                                        productListApi.queryProductInfoById(orderGoods.getGoodsId());
                                if (RestResult.checkIsSuccess(productAfterInfoByIdResponseRestResult)) {
                                    ProductAfterInfoByIdResponse productAfterInfoByIdResponse = productAfterInfoByIdResponseRestResult.getData();
                                    if (productAfterInfoByIdResponse != null && productAfterInfoByIdResponse.getPickFlag() == 1) {
                                        FrontOrderGoodsInfo frontOrderGoodsInfo = new FrontOrderGoodsInfo();
                                        BeanUtils.copyProperties(orderGoods, frontOrderGoodsInfo);
                                        goodsInfoList.add(frontOrderGoodsInfo);
                                    }
                                }
                            }
                            if (CollectionUtils.isNotEmpty(goodsInfoList)) {
                                BeanUtils.copyProperties(order, orderDetailInfo);
                                orderDetailInfo.setGoodsInfoList(goodsInfoList);
                            }
                        }
                        if (orderDetailInfo != null && orderDetailInfo.getParentOrderNo() != null) {
                            frontOrderDetailInfoList.add(orderDetailInfo);
                        }
                    }
                }
                if (CollectionUtils.isNotEmpty(frontOrderDetailInfoList)) {
                    frontAllOrderInfo.setOrderList(frontOrderDetailInfoList);
                    frontAllOrderInfoList.add(frontAllOrderInfo);
                }
            }
        }

        return RestResult.success(frontAllOrderInfoList);
    }

    @Override
    public RestResult<List<OrderDeliverDetail>> queryDeliverDetail(OrderDeliverDetailRequest request) {
        log.info("查询交货单明细，request={}", JSON.toJSONString(request));
        return executeQuery(() -> {
            OrderDeliverDetail orderDeliverDetailQ = new OrderDeliverDetail();
            orderDeliverDetailQ.setDeliverNo(request.getDeliverNo());
            log.debug("--查询订单状态统计-查询前-查询交货单明细---");
            Long start = System.currentTimeMillis();
            List<OrderDeliverDetail> orderDeliverDetailList = orderDeliverDetailMapper.query(orderDeliverDetailQ);
            log.debug("--查询订单状态统计-查询后-查询交货单明细---");
            Long end = System.currentTimeMillis();
            log.debug("--查询订单状态统计-查询后-查询交货单明细,耗时:{}--", end - start);
            return orderDeliverDetailList;
        });
    }

    @Override
    public RestResult<OrderDetailInfo> getOrderInfoByOrderNo(String orderNo) {
        Order order = orderMapper.queryByOrderNo(orderNo);
        //获取订单相关信息
        OrderDetailInfo orderDetailInfo = new OrderDetailInfo();
        if (order != null) {
            orderDetailInfo.setOrderNo(order.getOrderNo());
            orderDetailInfo.setBuyTime(order.getBuyTime());
            orderDetailInfo.setActualPayTotalAmount(order.getActualPayTotalAmount());
            OrderParent orderParent = new OrderParent();
            orderParent.setParentOrderNo(order.getParentOrderNo());
            List<OrderParent> orderParentList = orderParentMapper.query(orderParent);
            if (CollectionUtil.isNotEmpty(orderParentList)) {
                orderDetailInfo.setReceiverName(orderParentList.get(0).getReceiverName());
                orderDetailInfo.setReceiverPhone(orderParentList.get(0).getReceiverPhone());
                StringBuffer receiverAddress = new StringBuffer();
                receiverAddress.append(orderParentList.get(0).getReceiverProvinceName()).append(orderParentList.get(0).getReceiverCityName())
                        .append(orderParentList.get(0).getReceiverRegionName()).append(orderParentList.get(0).getReceiverAddress());
                orderDetailInfo.setReceiverAddress(receiverAddress.toString());
            }
            //获取订单 商品信息
            OrderGoods orderGoods = new OrderGoods();
            orderGoods.setOrderNo(orderNo);
            List<OrderGoods> orderGoodsList = orderGoodsMapper.query(orderGoods);
            if (CollectionUtil.isNotEmpty(orderGoodsList)) {
                List<Map<String, String>> productInfo = new ArrayList<>();
                for (OrderGoods goods : orderGoodsList) {
                    RestResult<ProductAfterInfoByIdResponse> goodsInfo = productListApi.queryProductInfoById(goods.getGoodsId());
                    if (goodsInfo.getData() != null) {
                        Map<String, String> goodsMap = new HashMap<>();
                        goodsMap.put("productId", String.valueOf(goods.getGoodsId()));
                        goodsMap.put("name", goodsInfo.getData().getChineseName());
                        goodsMap.put("pictureUrl", goodsInfo.getData().getPictureUrl());
                        goodsMap.put("goodsProperty", goodsInfo.getData().getPropertyName());
                        goodsMap.put("goodsNum", String.valueOf(goods.getGoodsNum()));
                        goodsMap.put("marketPrice", goodsInfo.getData().getMarketPrice().toString());
                        goodsMap.put("availablePrice", goods.getBuyUnitPrice().toString());
                        RestResult<MemStoreResponse> storeInfo = managerStoreApi.getStoreInfo(goodsInfo.getData().getDeptId());
                        if (storeInfo != null && storeInfo.getData() != null) {
                            goodsMap.put("storeName", storeInfo.getData().getStoreName());
                            goodsMap.put("storeLogo", storeInfo.getData().getStoreLogo());
                        }
                        productInfo.add(goodsMap);
                    }
                }
                orderDetailInfo.setProductInfo(productInfo);
            }
        }
        return RestResult.success(orderDetailInfo);
    }

    @Override
    public RestResult queryOrderNoByDeliverNo(OrderDeliverDetailRequest request) {
        return RestResult.success(orderDeliverMapper.queryOrderNoByDeliverNo(request));
    }


}
